import React from 'react';
import {Modal, Form, Input, InputNumber, Switch, Alert, TreeSelect} from 'antd';
import form, {emptyRule} from '../_/form';
import redux from '../_/redux';
import {context} from '../_';
import _name, {_title} from './dev';
const FormItem = Form.Item;
const dataName = 'dataEdit';

function getTree(nodes, pid = null, sid) {
    const children = [];
    for (const i in nodes) {
        const node = nodes[i];
        if (node.Pid === pid && node.Id !== sid) {
            children.push({value: node.Id + '', label: node.Name, children: getTree(nodes, node.Id, sid), node});
        }
    }
    return children;
}

@context('params')
@form({
    data: dataName,
    newData: {
        Status: true,
        DisplayOrder: 0
    }
})
@redux(_name, {
    data: ({[dataName]: data}) => (data ? data.Id : '-'),
    actions: ['create', 'modify']
})
@redux(_name, {
    data: '_',
    prefix: 'all'
})
export default class EditorModel extends React.Component {
    state = {};

    componentWillReceiveProps(props) {
        const {[dataName]: data} = props;
        const {[dataName]: rawdata} = this.props;
        if (data !== rawdata) {
            this.setState({errMsg: false});
        }
    }


    render() {
        const {[dataName]: data = {}, form, onState, alldata = []} = this.props;
        const treeData = getTree(alldata, null, data.Id);
        const {getFieldDecorator: fp} = form;
        const formItemLayout = {
            labelCol: {span: 6},
            wrapperCol: {span: 14},
        };
        const onOk = () => {
            form.validateFieldsAndScroll((err, vals) => {
                if (err) {
                    this.setState({errMsg: true});
                } else {
                    this.setState({errMsg: false});
                    onState("save");
                    vals.Pid = vals.Pid === undefined ? null : vals.Pid;
                    if (this.props.isNew) {
                        this.props.create(vals, this.props);
                    } else {
                        this.props.modify(vals, this.props);
                    }
                }
            });
        };
        const onCancel = () => {
            form.setFieldsValue(data);
            onState("cancel");
        };

        const nameInputOption = {
            rules: [{min: 1, max: 200}]
        };

        const alert = this.state.errMsg ?
            (<Alert message="输入项有错误,请检查后再试!" type="error" showIcon/>)
            : "";
        return (
            <Modal
                title={this.props.title}
                okText="保存"
                maskClosable={false}
                onOk={onOk}
                onCancel={onCancel}
                visible={this.props.visible}
                wrapClassName={`${_name}Modal`}
            >
                {alert}
                <Form>
                    {fp("Id")(<Input type="hidden"/>)}
                    <FormItem {...formItemLayout} label={`上级${_title}`}>
                        {fp("Pid")(
                            <TreeSelect
                                allowClear
                                treeData={treeData}
                                placeholder={`上级${_title}`}
                                treeDefaultExpandAll
                            />
                        )}
                    </FormItem>
                    <FormItem {...formItemLayout} label={`${_title}编码`}>
                        {fp("Code", {
                            validate: [
                                {
                                    rules: [
                                        emptyRule(),
                                        {min: 1, max: 50}]
                                }
                            ]
                        })(<Input />)}
                    </FormItem>
                    <FormItem {...formItemLayout} label={`${_title}名称`}>
                        {fp("Name", nameInputOption)(<Input />)}
                    </FormItem>
                    <FormItem {...formItemLayout} label="图标">
                        {fp("Icon")(<Input />)}
                    </FormItem>
                    <FormItem {...formItemLayout} label="显示顺序">
                        {fp("DisplayOrder")(<InputNumber />)}
                    </FormItem>
                    <FormItem {...formItemLayout} label="状态">
                        {fp("Status", {valuePropName: 'checked'})(
                            <Switch checkedChildren={'启动'} unCheckedChildren={'停用'}/>
                        )}
                    </FormItem>
                </Form>
            </Modal>
        );
    }
}
